package com.example.petshopping.ui.follows;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petshopping.R;
import com.example.petshopping.ui.follows.adapter.FollowedStoreAdapter;
import com.example.petshopping.ui.follows.adapter.StoreAdapter;
import com.example.petshopping.ui.follows.model.Store;
import com.example.petshopping.ui.follows.model.StoreProduct;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FollowsActivity extends AppCompatActivity implements StoreAdapter.OnStoreActionListener, FollowedStoreAdapter.OnStoreActionListener {

    private TabLayout tabLayout;
    private RecyclerView rvStoreList;
    private StoreAdapter storeAdapter;
    private FollowedStoreAdapter followedStoreAdapter;
    private List<Store> storeList = new ArrayList<>();
    
    // 状态布局
    private View layoutEmptyState;
    private View layoutNetworkError;
    private Button btnRetry;
    
    // 当前页面状态
    private enum PageState { NORMAL, EMPTY, ERROR }
    private PageState currentPageState = PageState.NORMAL;
    
    // 模拟网络状态，实际应用中应该通过网络请求判断
    private boolean hasNetworkError = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_follows);
        
        initViews();
        setupTabListeners();
        loadStoreData();
        setupRecyclerView();
        
        // 处理默认标签页参数
        handleDefaultTabIntent();
    }
    
    private void handleDefaultTabIntent() {
        // 获取Intent中的默认标签页参数
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("default_tab")) {
            int defaultTab = intent.getIntExtra("default_tab", 0);
            // 确保标签页索引有效
            if (defaultTab >= 0 && defaultTab < tabLayout.getTabCount()) {
                TabLayout.Tab tab = tabLayout.getTabAt(defaultTab);
                if (tab != null) {
                    tab.select();
                }
            }
        } else {
            // 如果没有指定标签页，则更新当前状态
            updatePageState();
        }
    }
    
    private void initViews() {
        // 初始化TabLayout
        tabLayout = findViewById(R.id.tab_layout);
        
        // 初始化RecyclerView
        rvStoreList = findViewById(R.id.rv_store_list);
        
        // 初始化状态布局
        layoutEmptyState = findViewById(R.id.layout_empty_state);
        layoutNetworkError = findViewById(R.id.layout_network_error);
        btnRetry = layoutNetworkError.findViewById(R.id.btn_retry);
        btnRetry.setOnClickListener(v -> onRetryClick());
        
        // 添加长按测试功能
        btnRetry.setOnLongClickListener(v -> {
            toggleTestMode();
            return true;
        });
        
        // 设置返回按钮
        ImageView btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> finish());
        
        // 默认选中第一个标签
        TabLayout.Tab tab = tabLayout.getTabAt(0);
        if (tab != null) {
            tab.select();
        }
    }
    
    private void setupTabListeners() {
        // 设置TabLayout的选项卡选中监听器
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                handleTabSelection(position);
                String[] tabNames = {"关注上新", "关注的店", "我的粉丝", "屏蔽的店"};
                Toast.makeText(FollowsActivity.this, "切换到" + tabNames[position] + "标签", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 不需要处理
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 如果需要，可以在此处理重新选择相同标签的情况
            }
        });
    }
    
    private void handleTabSelection(int position) {
        switch (position) {
            case 0: // 关注上新
                showFollowsNewTab();
                break;
            case 1: // 关注的店
                showFollowedStoresTab();
                break;
            case 2: // 我的粉丝
            case 3: // 屏蔽的店
                // 暂时使用空状态展示
                setPageState(PageState.EMPTY);
                break;
        }
    }
    
    private void showFollowsNewTab() {
        // 显示关注上新标签内容
        if (storeAdapter == null) {
            return;
        }
        
        // 使用StoreAdapter适配器
        rvStoreList.setAdapter(storeAdapter);
        storeAdapter.filterByTab(0);
        
        // 根据数据更新页面状态
        boolean hasData = storeAdapter.getItemCount() > 0;
        if (hasNetworkError) {
            setPageState(PageState.ERROR);
        } else if (!hasData) {
            setPageState(PageState.EMPTY);
        } else {
            setPageState(PageState.NORMAL);
        }
    }
    
    private void showFollowedStoresTab() {
        // 显示关注的店标签内容
        if (followedStoreAdapter == null) {
            followedStoreAdapter = new FollowedStoreAdapter(this, storeList, this);
            followedStoreAdapter.filterFollowedStores();
        }
        
        // 使用FollowedStoreAdapter适配器
        rvStoreList.setAdapter(followedStoreAdapter);
        
        // 根据数据更新页面状态
        boolean hasData = followedStoreAdapter.getItemCount() > 0;
        if (hasNetworkError) {
            setPageState(PageState.ERROR);
        } else if (!hasData) {
            setPageState(PageState.EMPTY);
        } else {
            setPageState(PageState.NORMAL);
        }
    }
    
    private void loadStoreData() {
        // 创建样例数据
        List<StoreProduct> products = Arrays.asList(
            new StoreProduct(R.drawable.pet_3, "432"),
            new StoreProduct(R.drawable.pet_2, "432"),
            new StoreProduct(R.drawable.pet_4, "432"),
            new StoreProduct(R.drawable.pet_5, "432")
        );
        
        // 已关注的店铺
        Store store1 = new Store();
        store1.setId(1);
        store1.setName("招财猫旺财狗");
        store1.setAvatarResourceId(R.drawable.yingwu);
        store1.setRating(5);
        store1.setFollowers("44万粉丝");
        store1.setFollowed(true);
        store1.setNewStore(false);
        store1.setProducts(products);
        store1.setTabIndex(0); // 关注上新
        storeList.add(store1);
        
        // 推荐关注的新店
        Store store2 = new Store();
        store2.setId(2);
        store2.setName("招财猫旺财狗");
        store2.setAvatarResourceId(R.drawable.yingwu);
        store2.setRating(5);
        store2.setFollowers("刚刚上新");
        store2.setFollowed(false);
        store2.setNewStore(true);
        store2.setProducts(products);
        store2.setTabIndex(0); // 关注上新
        storeList.add(store2);
        
        // 已关注的店铺
        Store store3 = new Store();
        store3.setId(3);
        store3.setName("招财猫旺财狗");
        store3.setAvatarResourceId(R.drawable.yingwu);
        store3.setRating(5);
        store3.setFollowers("刚刚上新");
        store3.setFollowed(true);
        store3.setNewStore(true);
        store3.setProducts(products);
        store3.setTabIndex(0); // 关注上新
        storeList.add(store3);
        
        // 推荐关注的店铺
        Store store4 = new Store();
        store4.setId(4);
        store4.setName("招财猫旺财狗");
        store4.setAvatarResourceId(R.drawable.yingwu);
        store4.setRating(5);
        store4.setFollowers("刚刚上新");
        store4.setFollowed(false);
        store4.setNewStore(true);
        store4.setProducts(products);
        store4.setTabIndex(0); // 关注上新
        storeList.add(store4);
    }
    
    private void setupRecyclerView() {
        storeAdapter = new StoreAdapter(this, storeList, this);
        rvStoreList.setLayoutManager(new LinearLayoutManager(this));
        rvStoreList.setAdapter(storeAdapter);
        
        // 默认显示"关注上新"标签下的店铺
        storeAdapter.filterByTab(0);
    }
    
    private void updatePageState() {
        int selectedTabPosition = tabLayout.getSelectedTabPosition();
        handleTabSelection(selectedTabPosition);
    }
    
    private void setPageState(PageState state) {
        currentPageState = state;
        
        // 根据状态显示/隐藏不同的视图
        switch (state) {
            case NORMAL:
                rvStoreList.setVisibility(View.VISIBLE);
                layoutEmptyState.setVisibility(View.GONE);
                layoutNetworkError.setVisibility(View.GONE);
                break;
                
            case EMPTY:
                rvStoreList.setVisibility(View.GONE);
                layoutEmptyState.setVisibility(View.VISIBLE);
                layoutNetworkError.setVisibility(View.GONE);
                break;
                
            case ERROR:
                rvStoreList.setVisibility(View.GONE);
                layoutEmptyState.setVisibility(View.GONE);
                layoutNetworkError.setVisibility(View.VISIBLE);
                break;
        }
    }
    
    private void onRetryClick() {
        // 模拟网络请求重试
        Toast.makeText(this, "正在重新加载数据...", Toast.LENGTH_SHORT).show();
        
        // 在实际应用中，这里应该执行网络请求
        // 为了演示，简单地将网络错误状态设为false
        hasNetworkError = false;
        updatePageState();
    }

    // 测试模式，用于演示不同状态
    private void toggleTestMode() {
        // 轮换不同状态：正常 -> 空状态 -> 错误状态 -> 正常
        switch (currentPageState) {
            case NORMAL:
                hasNetworkError = false;
                setPageState(PageState.EMPTY);
                Toast.makeText(this, "切换到空状态", Toast.LENGTH_SHORT).show();
                break;
            case EMPTY:
                hasNetworkError = true;
                setPageState(PageState.ERROR);
                Toast.makeText(this, "切换到错误状态", Toast.LENGTH_SHORT).show();
                break;
            case ERROR:
                hasNetworkError = false;
                setPageState(PageState.NORMAL);
                Toast.makeText(this, "切换到正常状态", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onFollowClick(Store store) {
        // 处理关注/取消关注按钮点击
        store.setFollowed(!store.isFollowed());
        storeAdapter.notifyDataSetChanged();
        
        // 如果当前是"关注的店"标签，需要更新显示
        if (tabLayout.getSelectedTabPosition() == 1 && followedStoreAdapter != null) {
            followedStoreAdapter.filterFollowedStores();
            updatePageState();
        }
        
        String message = store.isFollowed() ? "已关注 " : "已取消关注 ";
        Toast.makeText(this, message + store.getName(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onEnterStoreClick(Store store) {
        // 处理进店按钮点击
        Toast.makeText(this, "进入店铺: " + store.getName(), Toast.LENGTH_SHORT).show();
    }
} 